<?php
// This file is part of Moodle - http://moodle.org/  
// 
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * This is a file part of MDL-19430:
 * "user-determined order and number of courses on myMoodle"
 * http://tracker.moodle.org/browse/MDL-19430
 * 
 * This requires MDL-17446 to work.
 * This file allows the user to move courses up and down on myMoodle
 *
 * @package local
 * @copyright 2009 Minh-Tam R. Nguyen (minhtam@minhtam.info)
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once('../config.php');
require_login();
global $CFG, $USER;

$id = required_param('id', PARAM_INT);
$mode = required_param('m', PARAM_ALPHA);
// there really isn't much point doing anything unless the data provided is right
if ((is_numeric($id)) && (($mode=='u') || ($mode=='d') || ($mode=='t') || ($mode=='b'))) {
	// some preliminary setup
	if ($USER->myorder == '') {
		$preforder = explode(',',$USER->mycourses); 
	} else {
		$preforder = explode(',',$USER->myorder); 
	}
	if ((is_numeric($id)) && (($mode=='u') || ($mode=='d'))) {
		// we're going to swap the course with it's neighbour. 
		$key = array_search($id,$preforder);
		if ($mode == 'u') {
			$key--; // the other neighbour
		}
		$toswap = array_slice($preforder,$key,2);
		$toswap =array_reverse($toswap);
		array_splice($preforder,$key,2,$toswap);
	} else if ((is_numeric($id)) && ($mode=='t')) { // end of is_numeric && mode u or d
		$key = array_search($id,$preforder);
		unset($preforder[$key]);
		array_unshift($preforder, $id);	        
	} else if ((is_numeric($id)) && ($mode=='b')) { // end of is_numeric && mode t
		$key = array_search($id,$preforder);
		unset($preforder[$key]);
		array_push($preforder, $id);	        
	} // end of is_numeric && mode b
		require_once('lib.php');
		$USER->myorder = set_myorder($USER->id,$preforder);
} // end of valid mode	
redirect($CFG->httpswwwroot.'/my/index.php');
